package com.leo.auth.exception;

import cn.hutool.json.JSONUtil;
import com.leo.common.core.enums.ExceptionCodeEnum;
import com.leo.common.core.model.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 自定义 匿名用户访问无权限资源时的异常处理
 * </p>
 *
 * @author ：Leo
 * @since ：2021-04-08 10:52
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        Result<Void> result = Result.error(ExceptionCodeEnum.AUTH_USER_NOT_LOGIN);
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
